package com.a2.appa3.ui.activity;


import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.a2.appa3.R;
import com.a2.appa3.global.HttpAdress;
import com.a2.appa3.global.Info;
import com.a2.appa3.model.CustomObserver;
import com.a2.appa3.model.network.HttpJsonUtils;
import com.a2.appa3.model.network.entity.req.ResUserInfo;
import com.a2.appa3.model.network.entity.req.Resaddfriend;
import com.a2.appa3.util.RoundImageView;
import com.a2.appa3.util.SYSOUtils;
import com.a2.appa3.util.WebSocketUtils2;

import org.json.JSONObject;

import java.net.URLEncoder;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.shihao.library.XStatusBarHelper;

public class SearchActivity extends BaseActivitySimple {

    @BindView(R.id.ivback)
    ImageView ivback;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.headerTitle)
    TextView headerTitle;
    @BindView(R.id.headerButton)
    ImageView headerButton;
    @BindView(R.id.headerButtonRoot)
    LinearLayout headerButtonRoot;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.user_img)
    RoundImageView userImg;
    @BindView(R.id.user_nikename)
    TextView userNikename;
    @BindView(R.id.user_code)
    TextView userCode;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.btnlin)
    LinearLayout btnlin;
    @BindView(R.id.commitbt)
    TextView commitbt;
    @BindView(R.id.canclebt)
    TextView canclebt;

    @BindView(R.id.users)
    LinearLayout users;
    @BindView(R.id.ground)
    LinearLayout ground;
    @BindView(R.id.groundname)
    TextView groundname;
    @BindView(R.id.deletefr)
    TextView deletefr;
    @BindView(R.id.insertground)
    ImageView insertground;
    private String userid;
    private String usertype;
    private String groundid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            //解决Android5.0以上，状态栏设置颜色后变灰的问题
            XStatusBarHelper.tintStatusBar(this, getResources().getColor(R.color.settingbg));
        }
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        headerTitle.setText("用户");
        headerButton.setImageResource(R.mipmap.setname);
        userid = getIntent().getStringExtra("username");
        usertype = getIntent().getStringExtra("usertype");
        groundid = getIntent().getStringExtra("groundid");
        headerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SearchActivity.this, changenameDiolog.class);
                intent.putExtra("nameid", userid + "");
                startActivity(intent);
            }
        });
        try {
            if (usertype.equals("users")) {
                searchfriend(userid);
            } else {
                headerTitle.setText(groundid + "");
                users.setVisibility(View.GONE);
                ground.setVisibility(View.VISIBLE);
                groundname.setText("您确定进入" + groundid + "群吗？");
                insertground.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            Info.mdatas.clear();
                            String str = "";
                            final JSONObject result = new JSONObject();
                            result.put("controller", "Action");
                            result.put("action", "openWindow");
                            result.put("type", "room");
                            result.put("id", userid + "");
                            SYSOUtils.sOut_("ContactsAdapter生成json为" + result.toString());
                            String text1 = URLEncoder.encode(result.toString(), "utf-8");
                            String encodeWord = null;
                            encodeWord = Base64.encodeToString(text1.getBytes("utf-8"), Base64.DEFAULT);
                            str = "type=ins&message=" + encodeWord;
                            SYSOUtils.sOut_("ContactsAdapter最终结果为" + str);
                            WebSocketUtils2.getInstance().sendMsg(str);
                            Intent intent = new Intent(SearchActivity.this, ChatActivity1.class);
                            intent.putExtra("chatname", groundid);
                            startActivity(intent);
                            finish();
                        } catch (Exception e) {
                        }
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        commitbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(userid)) {
                    insertmyfriend(userid);
                }
            }
        });
        canclebt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        deletefr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteusers();
            }
        });
    }

    /**
     * 删除好友
     */
    private void deleteusers() {
        HttpJsonUtils.getHttpApiInstance()
                .delUserFriends(HttpAdress.getuseAdress() + "api/chatapi/User/delUserFriends", userid, Info.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<Resaddfriend>() {
                    @Override
                    protected void onCustomNext(Resaddfriend resaddfriend) {

                        if (resaddfriend.getCode() == 0) {
                            Toast.makeText(SearchActivity.this, "删除成功", Toast.LENGTH_LONG).show();
                            finish();
                        } else {
                            Toast.makeText(SearchActivity.this, "" + resaddfriend.getMsg(), Toast.LENGTH_LONG).show();
                            finish();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_search;
    }

    /**
     * 添加好友
     *
     * @param result
     */
    private void insertmyfriend(String result) {
        HttpJsonUtils.getHttpApiInstance()
                .insertmyfriend(HttpAdress.getuseAdress() + "api/chatapi/User/addUserFriendsLog", result, Info.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<Resaddfriend>() {
                    @Override
                    protected void onCustomNext(Resaddfriend resaddfriend) {
                        if (resaddfriend.getCode() == 0) {
                            Toast.makeText(SearchActivity.this, "添加成功，请等待回应", Toast.LENGTH_LONG).show();
                            finish();
                        } else {
                            Toast.makeText(SearchActivity.this, "" + resaddfriend.getMsg(), Toast.LENGTH_LONG).show();
                            finish();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }

    /**
     * 搜索好友
     *
     * @param str
     */
    private void searchfriend(String str) {
        HttpJsonUtils.getHttpApiInstance()
                .searchUserInfo(HttpAdress.getuseAdress() + "api/chatapi/User/searchUserInfo", str, Info.Token, "1")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<ResUserInfo>() {
                    @Override
                    protected void onCustomNext(ResUserInfo resUserInfo) {
                        try {
                            if (resUserInfo.code == 0) {
                                Glide.with(SearchActivity.this).load(HttpAdress.getuseAdress() + resUserInfo.data.img
                                ).error(R.mipmap.default_head).into(userImg);
                                userCode.setText(resUserInfo.data.username);
                                userNikename.setText(resUserInfo.data.nickname);
                                headerTitle.setText(resUserInfo.data.remark);
                                userName.setText(resUserInfo.data.remark);
                                if (resUserInfo.data.is_friend != 1) {
                                    btnlin.setVisibility(View.VISIBLE);
                                    headerButton.setVisibility(View.GONE);
                                    deletefr.setVisibility(View.GONE);
                                } else {
                                    btnlin.setVisibility(View.GONE);
                                    headerButton.setVisibility(View.VISIBLE);
                                    deletefr.setVisibility(View.VISIBLE);
                                }
                            } else {
                                Toast.makeText(SearchActivity.this, "没查询到您所搜索的信息", Toast.LENGTH_LONG).show();
                            }
                        } catch (Exception e) {

                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(userid)) {
            if (usertype.equals("users")) {
                searchfriend(userid);
            }
        }
    }
}
